﻿using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Collections.Generic;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint.Utilities;

namespace SPFileSize.ListItemSizeWebPart
{
    [ToolboxItem(false)]
    public partial class ListItemSizeWebPart : System.Web.UI.WebControls.WebParts.WebPart
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeControl();
        }


        private string SiteCollectionUrl = "";
        string childnode = "";
        double sitecollectionsize = 0;
        string domId;
        string childFormatedNode = "";
        Dictionary<string, SPFileSizeInfo> webinfo = new Dictionary<string, SPFileSizeInfo>();
        

        protected void Page_Load(object sender, EventArgs e)
        {
            SiteCollectionUrl = SPContext.Current.Site.Url;


            using (SPSite site = new SPSite(SiteCollectionUrl))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    GetWebInfo(web);
                    GetWebInfo(web,"20px");

                }
            }
        }

        

        private void GetWebInfo(SPWeb web)
        {
            SPFileSizeInfo o =  GetDocItemSize(web);
            webinfo.Add(web.ID.ToString(),o);
            sitecollectionsize += o.ContainerSize;
            foreach (SPWeb subweb in web.Webs)
            {
                GetWebInfo(subweb);
                
            }
            
        }

        private void GetWebInfo(SPWeb web, string indent)
        {
            //SPFileSizeInfo o = GetDocItemSize(web);
            SPFileSizeInfo o = webinfo[web.ID.ToString()];

            string formatednode = "";


            string rootdiv = string.Format("<div style='display:none;margin-left:{1}' class='{0}' width='600px'>" + PopulateTree(o, "0px", o.ContainerGuid) + "</div>", web.ID.ToString(), indent);
            formatednode = string.Format(@"<table align='left' valign='top' ><tr><td style='cursor:hand'  onclick=""$('.{1}').toggle();$(this).find('img').toggle();"" >
                                                            <img class='expand' style=''  src='{3}/Style%20Library/FileSizeInfoWebpart/plus.png'/>                                
                                                            <img class='collapse' style='display:none;' src='{3}/Style%20Library/FileSizeInfoWebpart/minus.png'/>
                                             </td><td>{0}</td></tr><tr><td colspan='2'>{2}</td></table>",
                        HtmlSizeInfo(web.Title, sitecollectionsize, o.ContainerSize, "#00CC66", "", web.Url), web.ID.ToString(), rootdiv,SiteCollectionUrl);

            divTreeView.InnerHtml += formatednode;
            childnode = "";
            foreach (SPWeb subweb in web.Webs)
            {
                GetWebInfo(subweb, "20px");

            }

        }

       

        private string PopulateTree(SPFileSizeInfo ListSizeInfo, string indent, string parentnode)
        {
            foreach (SPFileSizeInfo iteminfo in ListSizeInfo.ItemSizeInfo)
            {

                string formatednode = "";
                //string domId = (parentnode == null) ? "id_" + Environment.TickCount.ToString() : "id_" + parentnode.Replace("-", "");
                if (iteminfo.ItemSizeInfo == null || iteminfo.ItemSizeInfo.Count == 0)
                {
                    childFormatedNode += string.Format("<div style='margin-left:" + indent + "'>" + "{0}</div>", HtmlSizeInfo(iteminfo.ItemTitle, ListSizeInfo.ContainerSize, iteminfo.ItemSize, "orange", "", iteminfo.ContainerPath), parentnode, domId);

                }
                else
                {
                    domId = Environment.TickCount.ToString();

                    formatednode = string.Format(@"<table align='left' valign='top' ><tr><td style='cursor:hand'  onclick=""toggleNode('id_{1}','cls{1}');$(this).find('img').toggle();"" >
                                                <img class='expand' style=''  src='{3}/Style%20Library/FileSizeInfoWebpart/plus.png'/>                                
                                                <img class='collapse' style='display:none;' src='{3}/Style%20Library/FileSizeInfoWebpart/minus.png'/>
                                 </td><td>{0}</td></tr></table>",
                        HtmlSizeInfo(iteminfo.ItemTitle, ListSizeInfo.ContainerSize, iteminfo.ItemSize, "#3399FF", "", iteminfo.ContainerPath), iteminfo.ContainerGuid, domId, SiteCollectionUrl);

                }


                childnode += "<div id='id_" + iteminfo.ContainerGuid + "' style='margin-left:" + indent + "'>" + formatednode + "</div>";
                //childnode += formatednode;
                if (iteminfo.ItemSizeInfo != null)
                {
                    PopulateTree(iteminfo, "40px", iteminfo.ContainerGuid);
                    childnode += "<div style='display:none' class='cls" + iteminfo.ContainerGuid + "'>" + childFormatedNode + "</div>";
                    childFormatedNode = "";
                }



            }
            return childnode;
        }


     


        private string HtmlSizeInfo(string itemtitle, double totalsize, double itemsize, string color, string tableid, string containerpath)
        {
            string html = "";
            string cssclass = "childnodetable_" + Guid.NewGuid().ToString();

            int width = Convert.ToInt32(Math.Ceiling(Convert.ToDouble((itemsize / totalsize) * 100)));
            if (width <= 0)
            {
                html = @"<table height='12px'  width='200px' style='border:1px solid black;color:black'>" +
                           "<tr>" +
                               "<td align='left'>0%</td><td></td>" +
                           "</tr>" +
                           "</table>";

            }
            else
            {
                html = @"<table height='12px' class='" + cssclass + "' width='200px' style='border:1px solid black;color:black'>" +
                           "<tr>" +
                               "<td width='" + width.ToString() + "%' style='background:" + color + ";'>" + width.ToString() + "%</td><td></td>" +
                           "</tr>" +
                           "</table>";

            }

            string html1 = @"<table  height='12px'  width='600px'>" +
                           "<tr>" +
                               "<td width='40%'><a target='_blank' href='" + containerpath + "'>" + itemtitle + "</a></td><td align='center' width='20%'>" + Math.Ceiling((itemsize / 1000)) + " KB" + "</td><td width='40%' align='right'>" + html + "</td>" +
                           "</tr>" +
                           "</table>";

            return html1;

        }




        private SPFileSizeInfo GetDocItemSize(SPWeb web)
        {
           

            SPFileSizeInfo ListSizeInfo = new SPFileSizeInfo();
            ListSizeInfo.ItemTitle = web.Title;
            ListSizeInfo.ItemPath = web.Url;
            ListSizeInfo.ItemSizeInfo = new List<SPFileSizeInfo>();
            

            foreach (SPList list in web.Lists)
            {

                if (list.BaseType == SPBaseType.DocumentLibrary)
                {
                   
                    SPFileSizeInfo itemsizeinfo = new SPFileSizeInfo();
                    itemsizeinfo.ItemTitle = list.Title;
                    itemsizeinfo.ContainerPath = list.DefaultViewUrl;
                    itemsizeinfo.ItemSizeInfo = new List<SPFileSizeInfo>();
                    itemsizeinfo.ContainerGuid = list.ID.ToString();
                    SPQuery query = new SPQuery();
                    query.ViewFields = "<FieldRef Name='File_x0020_Size' /><FieldRef Name='Title' /><FieldRef Name='LinkTitle' />";

                    query.ViewAttributes = "Scope=\"Recursive\"";

                    SPListItemCollection items = list.GetItems(query);
                    foreach (SPListItem listitem in items)
                    {
                        SPFileSizeInfo listitemsizeinfo = new SPFileSizeInfo();

                        listitemsizeinfo.ItemTitle = listitem["Name"].ToString();
                        listitemsizeinfo.ContainerPath = list.DefaultViewUrl;
                        listitemsizeinfo.ItemID = listitem.ID;
                        listitemsizeinfo.ItemPath = listitem.Url;
                        //listitemsizeinfo.ItemSize = listitem.File.Length;
                        listitemsizeinfo.ItemSize = Convert.ToDouble(listitem["File_x0020_Size"]);
                        //string filesize = listitem["File_x0020_Size"].ToString();
                        //LiteralControl control1 = new LiteralControl();
                        //control1.Text = listitemsizeinfo.ItemTitle + " size:" + listitemsizeinfo.ItemSize.ToString() + "</br>";
                        //this.Controls.Add(control1);

                        /*
                        foreach (SPFileVersion fileversion in listitem.File.Versions)
                        {
                            listitemsizeinfo.ItemSize += fileversion.Size;
                        }

                        */
                        itemsizeinfo.ItemSizeInfo.Add(listitemsizeinfo);


                    }

                    itemsizeinfo.ItemSize = itemsizeinfo.ContainerSize;
                    ListSizeInfo.ItemSizeInfo.Add(itemsizeinfo);
                }
            }

            
            return ListSizeInfo;

        }
    }



}
